<?php
/**
 * Created by PhpStorm.
 * User: Leen
 * Date: 16/01/29
 * Time: 上午11:29
 */

namespace App\Repositories;
use App\Exceptions\Interfaces\AddressServiceException;
use App\Services\Allinpay\Services\Response;
use \Exception;
use App\Exceptions\Interfaces\SmsSendErrorException;

use Log;
use App\Interfaces\ShortMessageService;
use App\Models\MessageCode;
use App\Services\SendSms;

class ShortMessageRepository implements  ShortMessageService
{

    protected $sendSmsClient;

    protected $codeLiveTime=600;

    public function __construct()
    {
        $sendSms = new SendSms();

        $this->sendSmsClient = $sendSms;

    }//end func __construct()

    /**
     * 发送注册验证码: 尊敬的用户您好，您本次操作的验证码为：#${数字,4-10位}#$，#${文本,4位}#$欢迎您的注册
     * @param array phoneNumbers 接收短信的手机号码数组
     * @param string content 变量短信内容
     * @return mixed
     */
    public function sendRegMsg($phoneNumbers){

        //生成随机短信字符串
        $str='1234567890';
        $randStr = str_shuffle($str);//打乱字符串
        $code= substr($randStr,0,4);//substr(string,start,length);
        //发送注册验证码

        $content = '尊敬的用户您好，您本次操作的验证码为：'.$code;

        $result = $this->sendSmsClient->regMsg($phoneNumbers, $content);

        if ($result['status']==1000){

            $sendtime = date('Y-m-d H:i:s',time());
            $param['send_time'] = $sendtime;
            $param['phone'] = $phoneNumbers;
            $param['code'] = $code;

            $messageCode = MessageCode::create($param);

            return $messageCode->id;

        }else{

            throw SmsSendErrorException('短信发送失败');
            return ;
        }//end if()


    }//end func sendShortMessage


    public function validateRegCode($message_code_id,$code){

        $messageCode = MessageCode::find($message_code_id);

        if ($messageCode){

            if ($code==$messageCode->code&&strtotime(date('Y-m-d H:i:s',time()))-strtotime($messageCode->send_time)<=$this->codeLiveTime){

                return true;
            }

        }else{

            return false;
        }


    }



}//end class